﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using WindowsPhonePostClient;
using System.Collections.ObjectModel;
using System.Windows.Controls.Primitives;

namespace MeetingFinder
{
    public partial class CreateMeetingForm : PhoneApplicationPage
    {

        private ObservableCollection<ServerUserMeetingSuggestion> userSuggestionList = new ObservableCollection<ServerUserMeetingSuggestion>();
        private Popup popup = new Popup();

        public CreateMeetingForm()
        {
            InitializeComponent();

            this.newMeetingSuggestionList.ItemsSource = userSuggestionList; 

        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            string projectGroupSelected = NavigationContext.QueryString["groupSelected"];
            string projectModuleSelected = NavigationContext.QueryString["moduleSelected"];
                
            this.groupSelected.Text = projectGroupSelected;
            this.moduleSelected.Text = projectModuleSelected;

            base.OnNavigatedTo(e);
        }

        private void submitButton_Click(object sender, RoutedEventArgs e)
        {
            string errorMessage = StringConstants.noMeetingSuggestionMsg;
            bool meetingIsValid = true;

            if (meetingLocationInput.Text == StringConstants.defaultUserInput)
            {
                meetingIsValid = false;
                errorMessage = StringConstants.meetingLocationNotSetMsg;
            }
            
            if (meetingDescriptionInput.Text == StringConstants.defaultUserInput)
            {
                meetingIsValid = false;
                errorMessage = StringConstants.meetingDescriptionNotSetMsg;
            }
            
            if (meetingTitleInput.Text == StringConstants.defaultUserInput)
            {
                meetingIsValid = false;
                errorMessage = StringConstants.meetingTitleNotSetMsg;
            }

            if (userSuggestionList.Count != 0)
            {
                foreach(ServerUserMeetingSuggestion item in userSuggestionList)
                    if (Convert.ToInt32(item._state) < 0 || Convert.ToInt32(item._state) > 5 || item._state == null)
                    {
                        meetingIsValid = false;
                        errorMessage = StringConstants.statusNotSetMsg;
                    }                

                if (meetingIsValid)
                {
                    var currentApp = App.Current as App;

                    string time = getDateTimeString();
                    groupSelected.Text = time;

                    Dictionary<string, object> meetingDetails = new Dictionary<string, object>();
                    meetingDetails.Add("title", meetingTitleInput.Text);
                    meetingDetails.Add("content", meetingDescriptionInput.Text);
                    meetingDetails.Add("creator_id", currentApp._userID);
                    meetingDetails.Add("group_id", currentApp._selectedProjectGroup._groupID);
                    //meetingDetails.Add("group_id", "1");//for now just set test value
                    meetingDetails.Add("is_confirmed", StringConstants._is_confirmed_FALSE);
                    meetingDetails.Add("is_completed", StringConstants.is_completed_FALSE);
                    meetingDetails.Add("f_location", userSuggestionList.ElementAt(0)._location);//sets meeting location from 1st meeting item
                    meetingDetails.Add("f_time", userSuggestionList.ElementAt(0)._time);//sets meeting time from 1st meeting item

                    PostClient proxy = new PostClient(meetingDetails);
                    proxy.DownloadStringCompleted += (senderNM, eNM) =>
                    {
                        if (eNM.Error == null)
                        {
                            //Process the result... 
                            string[] data = eNM.Result.Split('\t');
                            string meetingID = data[0];

                            //send user suggested meeting timings
                            foreach (ServerUserMeetingSuggestion meetingSuggestion in userSuggestionList)
                            {
                                Dictionary<string, object> userSuggestion = new Dictionary<string, object>();

                                userSuggestion.Add("meeting_id", meetingID);
                                userSuggestion.Add("time", meetingSuggestion._time);
                                userSuggestion.Add("location", meetingSuggestion._location);
                                userSuggestion.Add("user_id", currentApp._userID);

                                PostClient userSuggestionProxy = new PostClient(userSuggestion);
                                userSuggestionProxy.DownloadStringAsync(new Uri(StringConstants._serverAddress + StringConstants._postNewUserSuggestionItemAPI, UriKind.Absolute));

                                //need to get returned user suggestion item id first
                                //need to post user choices for meeting item
                                userSuggestionProxy.DownloadStringCompleted += (senderUS, eUS) =>
                                {
                                    if (eUS.Error == null)
                                    {
                                        var result = eUS.Result;
                                        string userSuggestionItemID = result.Split('\t', '\n')[4];

                                        //send new user choice
                                        Dictionary<string, object> userChoice = new Dictionary<string, object>();

                                        userChoice.Add("item_id", userSuggestionItemID);
                                        userChoice.Add("user_id", currentApp._userID);
                                        userChoice.Add("state", meetingSuggestion._state);

                                        PostClient userChoiceProxy = new PostClient(userChoice);
                                        userChoiceProxy.DownloadStringAsync(new Uri(StringConstants._serverAddress + StringConstants._postUpdateUserSuggestionChoiceAPI, UriKind.Absolute));
                                    }
                                };
                            }

                            //show pop telling user new meeting created
                            //navigate back to main page
                            popup.Height = 300;
                            popup.Width = 400;
                            popup.VerticalOffset = 100;
                            MeetingCreatedPopup control = new MeetingCreatedPopup();
                            popup.Child = control;
                            popup.IsOpen = true;

                            control.MeetingCreatedTextBox.Text = "New Meeting Created";

                            control.NewMeetingCreatedButtonOK.Click += (s, args) =>
                            {
                                popup.IsOpen = false;
                                this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));

                            };

                        }

                    };
                    proxy.DownloadStringAsync(new Uri(StringConstants._serverAddress + StringConstants._postNewMeetingAPI, UriKind.Absolute));
                }
                else
                {
                    popup.Height = 300;
                    popup.Width = 400;
                    popup.VerticalOffset = 100;
                    MeetingCreatedPopup control = new MeetingCreatedPopup();
                    popup.Child = control;
                    popup.IsOpen = true;

                    control.MeetingCreatedTextBox.Text = errorMessage;

                    control.NewMeetingCreatedButtonOK.Click += (s, args) =>
                    {
                        popup.IsOpen = false;
                    };
                }
            }
            else
            {
                popup.Height = 300;
                popup.Width = 400;
                popup.VerticalOffset = 100;
                MeetingCreatedPopup control = new MeetingCreatedPopup();
                popup.Child = control;
                popup.IsOpen = true;

                control.MeetingCreatedTextBox.Text = "Please Enter a suggestion for meeting time and location";

                control.NewMeetingCreatedButtonOK.Click += (s, args) =>
                {
                    popup.IsOpen = false;
                };
            }           
            
        }
        
        private void addUserSuggestionButton_Click(object sender, RoutedEventArgs e)
        {
            if (userSuggestionList.Count == 0)
            {
                ServerUserMeetingSuggestion userMeetingSuggestion = new ServerUserMeetingSuggestion();

                //set meeting ID after server returns ID
                userMeetingSuggestion._location = meetingLocationInput.Text;
                userMeetingSuggestion._time = getDateTimeString();

                userSuggestionList.Add(userMeetingSuggestion);
            }
            else
            {
                bool userSuggestionExists = false;

                //check if new user suggestion already exists
                foreach (ServerUserMeetingSuggestion currentSuggestion in userSuggestionList)
                {
                    if (currentSuggestion._time == getDateTimeString() && currentSuggestion._location == meetingLocationInput.Text)
                            userSuggestionExists = true;                                   
                }

                if (!userSuggestionExists)
                {
                    ServerUserMeetingSuggestion userMeetingSuggestion = new ServerUserMeetingSuggestion();

                    //set meeting ID after server returns ID
                    userMeetingSuggestion._location = meetingLocationInput.Text;
                    userMeetingSuggestion._time = getDateTimeString();

                    userSuggestionList.Add(userMeetingSuggestion);
                }
                else
                {
                    popup.Height = 300;
                    popup.Width = 400;
                    popup.VerticalOffset = 100;
                    MeetingCreatedPopup control = new MeetingCreatedPopup();
                    popup.Child = control;
                    popup.IsOpen = true;

                    control.MeetingCreatedTextBox.Text = "Meeting Suggestion Already Exists";

                    control.NewMeetingCreatedButtonOK.Click += (s, args) =>
                    {
                        popup.IsOpen = false;
                    };
                }
            }
            
        }

        private string getDateTimeString()
        {
            string dateTimeString = dateInput.ValueString + " " + timeInput.ValueString;
            DateTime meetingDateTime = Convert.ToDateTime(dateTimeString);
            string time = String.Format("{0:u}", meetingDateTime);

            return time.Substring(0, time.Length - 1);//to remove special character 'Z' at the end
        }

        private void PhoneApplicationPage_Loaded_1(object sender, RoutedEventArgs e)
        {

        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            // If the currently displayed dialog is a pop-up, dialog etc., and
            // a Back Key Press occurs, then "close" the pop-up or dialog, and prevent GoBack.
            if (popup.IsOpen == true)
            {
                popup.IsOpen = false;                   // Hide the popup
                e.Cancel = true;                    // Cancel subsequent BackKey navigation
                LayoutRoot.IsHitTestVisible = true; // Restore mouse hit on main page
            }
            base.OnBackKeyPress(e); // Call base
        }

        private void removeUserSuggestionButton_Click(object sender, RoutedEventArgs e)
        {
            ServerUserMeetingSuggestion data = (sender as Button).DataContext as ServerUserMeetingSuggestion;
            ListBoxItem pressedItem = this.newMeetingSuggestionList.ItemContainerGenerator.ContainerFromItem(data) as ListBoxItem;
            if (pressedItem != null)
            {
                userSuggestionList.Remove(data);

            }
        }


    }

    
}